import { defineStore } from 'pinia'
import { checkToken } from '@/api/auth'
import { StorageEnum } from '@common/enums'
import type { User } from '@/api/interface/user'

interface AuthState {
  user: User | null
  isLoggedIn: boolean
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    isLoggedIn: false,
  }),
  actions: {
    async checkLogin() {
      try {
        const response = await checkToken()
        this.isLoggedIn = true
        this.user = response.user
        return {
          isLoggedIn: true,
          token: response.token,
          user: response.user,
        }
      } catch (error) {
        this.logout()
        return false
      }
    },

    logout() {
      localStorage.removeItem(StorageEnum.AUTH_TOKEN)
      localStorage.removeItem(StorageEnum.USER_INFO)
      this.user = null
      this.isLoggedIn = false
    },
  },
})
